
/**
 * Created by zhangxiaoming on 18/4/17.
 */

var http = require('http');
var https = require('https');
var cheerio = require('cheerio');
var charset = require("superagent-charset"); //gbk编码
var agent = require("superagent"); //gbk编码
var fs = require('fs');
var date = new Date();
const json2xls = require('json2xls');  //转excel

var bigClass = "index";

var creatHtml='./content/' + bigClass + date.getDate() +'.html';

// var filepath = './content/css.html';
// fs.unlink(filepath, function(err){
//      if(err){
//           throw err;
//      }
//      console.log('文件:'+filepath+'删除成功！');
// })


//ctrl+c  时执行保存
process.on('SIGINT', function () {
    console.log('Exit now!');
    createdFile()
    process.exit();
});


const createdTime = date.getFullYear() + '' + date.getMonth() + '' + date.getDate() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();
console.log("时间",date.getHours())
charset(agent); //

var codeArray = [
{ "Code": "002190", "name": "农银新能源主题" },
{ "Code": "400015", "name": "东方新能源汽车混合" },
{ "Code": "005669", "name": "前海开源公用事业股票" },
{ "Code": "160632", "name": "腾华酒指数A" },
{ "Code": "161725", "name": "招商中证白酒" },
{ "Code": "001631", "name": "天弘中证食品饮料指数A" },
{ "Code": "001632", "name": "天弘中证食品饮料指数C" },
{ "Code": "009565", "name": "汇安消费龙头混合C" },
{ "Code": "003096", "name": "中欧医疗健康混合C" },
{ "Code": "162412", "name": "中欧医疗健康混合C" },
{ "Code": "005827", "name": "中欧医疗健康混合C" },
{ "Code": "519732", "name": "中欧医疗健康混合C" },
{ "Code": "005106", "name": "中欧医疗健康混合C" },
{ "Code": "519919", "name": "中欧医疗健康混合C" },
{ "Code": "007154", "name": "中欧医疗健康混合C" },
{ "Code": "519116", "name": "中欧医疗健康混合C" },
{ "Code": "003634", "name": "中欧医疗健康混合C" },
{ "Code": "164403", "name": "中欧医疗健康混合C" },
{ "Code": "163402", "name": "中欧医疗健康混合C" },
{ "Code": "005968", "name": "中欧医疗健康混合C" },
{ "Code": "460005", "name": "中欧医疗健康混合C" },
{ "Code": "001938", "name": "中欧医疗健康混合C" },
{ "Code": "001644", "name": "中欧医疗健康混合C" },
{ "Code": "004997", "name": "中欧医疗健康混合C" },
{ "Code": "007192", "name": "中欧医疗健康混合C" },
{ "Code": "160630", "name": "中欧医疗健康混合C" },
{ "Code": "005038", "name": "中欧医疗健康混合C" },
{ "Code": "000597", "name": "中欧医疗健康混合C" }
];



codeArray.map((item,key) => {

    if(key==1){
        let head="<meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0'>"+
        "<meta name='apple-mobile-web-app-capable' content='yes'>"+
        "<meta name='apple-mobile-web-app-status-bar-style' content='black'>";
        let deps=head+"<link rel='stylesheet' type='text/css' href='./css/index.css'/>"
        fs.writeFile(creatHtml, deps, { 'flag': 'a' },function (err) {
        });
    }
    currentFundcode(item.Code)
    
})






function getInfoMao(data) {
    console.log(data.url)
    agent.get(data.url).charset('utf-8').end(function (err, res) {
        if (res) {
           
            filterHtml(res.text, data.fundObj);  
        } else {
        }

    });
}

function currentFundcode(code){
    var url = "https://fund.eastmoney.com/" + code + ".html";
    https.get(`https://fundgz.1234567.com.cn/js/`+code+`.js`, (response) => {
    
        console.log(`状态码: ${response.statusCode}`);
        // console.log(`响应头: ${JSON.stringify(response.headers)}`);
        
        if (response.statusCode!==200){
            // 如果不想读取数据一定记得手动消费哦
            response.resume();
            return;
        }
        
        response.setEncoding('utf8');
        let body = '';
        response.on('data', (chunk) => {
            let tempData=chunk;
            tempData=tempData.replace(/jsonpgz|{|}|\(|\)|"/g,"").split(",");
            let fundArray=[];
            let fundObj={};
            tempData.map(item=>{
                let temp=item.split(":");
                fundArray.push(temp)
            }) 
            fundArray.map(item=>{
                if(item[0]=="fundcode"){
                    fundObj.fundcode=item[1]
                }
                if(item[0]=="name"){
                    fundObj.name=item[1]
                }
                if(item[0]=="jzrq"){
                    fundObj.jzrq=item[1]
                }
                if(item[0]=="gszzl"){
                    fundObj.gszzl=item[1]
                }
                
            })
           
            console.log("---------fundObj------------",fundObj)
            getInfoMao({ "url": url, "fundObj": fundObj })
            body += chunk;
        });
        response.on('end', () => {
            // console.log(`响应主体: ${body}`);
           
            
            
        });
     
    }).on('error', (e) => {
        console.error(`请求出现问题: ${e.message}`);
    });
    
}


function filterHtml(html, fundObj) {
    var $ = cheerio.load(html);
    var lilv = $("#Div2 tbody tr td span");  //获取文章列表
    var spaceNum = 0;
    var lilvArray = [];
    var dadyTime = $("#Div2 tbody tr .alignLeft");
    let HoursNum=date.getHours();
    // if(HoursNum>10&&HoursNum<15){
    //     spaceNum= parseFloat(fundObj.gszzl)
    // }else{
    //     spaceNum=0
    // }
   
    for (var i = 0; i < dadyTime.length; i++) {
        if (i > 0 && i < 12) {
            lilvArray.push({ "date": dadyTime.eq(i).text() })
        }

    }

    for (var i = 0; i < lilvArray.length; i++) {

        let lilvText = parseFloat(lilv.eq(i).text().replace("%", ""));
        lilvArray[i].lilv = lilvText;

        spaceNum += lilvText;
        lilvArray[i].spaceNum = spaceNum.toFixed(2);
    }

    console.log(lilvArray)
    computerHandle(lilvArray, fundObj)
    return false

}


function computerHandle(data, fundObj) {
    var redNum = 0;
    var redText = 0;
    var greenNum = 0;
    var greenText = 0;
    var deps = '';
    var greenArr = [];
    var spaceNum = 0;
    var html = "";
    var isAdd=true;
    data.map((item, index) => {
        let daty
        if (item.lilv < 0) {
            isAdd=false;
           
        }else{
            isAdd=true; 
            spaceNum=0;
        }
        //跌幅相近的几天累计
        if(!isAdd){
            spaceNum+=item.lilv;
        }

        if (item.lilv < 0) {
            html += "<tr data-index=" + index + "><td>" + item.date + "</td><td>" + item.lilv + "</td><td>近" + index + "天</td><td class=green_font>" + item.spaceNum + "</td><td class=green_font>" + spaceNum.toFixed(2) + "</td></tr>"

        } else {
            html += "<tr data-index=" + index + "><td>" + item.date + "</td><td>" + item.lilv + "</td><td>近" + index + "天</td><td>" + item.spaceNum + "</td><td></td></tr>"

        }

        if (item.lilv > 0) {
            redNum++;
            redText = redText + item.lilv;
        }

        if (item.lilv < 0) {
            greenNum++;
            greenText = greenText + item.lilv;
            item.indexNum = index;
            greenArr.push(item)
        }

    })

    greenArr.sort(function (a, b) { return a.lilv - b.lilv }); //跌浮最大的排序
    
    let textNum="";
    if(fundObj.gszzl>=0){
        textNum= ":<font class='f-red'>涨"+fundObj.gszzl+"</font>" 
    }else{
        textNum= ":<font class='f-green'>跌"+fundObj.gszzl+"</font>" 
    }
    let totalNum=(greenText+redText).toFixed(2);  //共计涨幅
    if(totalNum>0){
        totalNum=":<font class='f-red'>涨"+totalNum+"</font>" 
    }else{
        totalNum=":<font class='f-green'>跌"+totalNum+"</font>"  
    }

    deps = "<a href='http://fundf10.eastmoney.com/jjjz_"+ fundObj.fundcode+".html'><div class='content'><h3>" + fundObj.name + fundObj.fundcode+"</h3><span>监控" + data.length + "天</span>--<span>涨" + redNum + "次,共" + redText.toFixed(2) +
        "</span>&nbsp;<span>跌" + greenNum + "次,跌" + greenText.toFixed(2) + "</span><br>" +
        "<span>今天"+textNum+"</span>----共"+totalNum+"<br>"+
        "<span>" + greenArr[0].date + "日跌" + greenArr[0].lilv + "最大距离现在" + greenArr[0].indexNum + "天" + 
        "<table>" + html + "</table></div></a>";
    fs.writeFile(creatHtml, deps, {
        'flag': 'a'
    }, function (err) {
        if (err) {
            console.log(err);
        }
        console.log('--------------------------文本文件----------------------------');
    });

}